import { login, userApi } from '@/api'
import { getToken, setToken, removeToken, getId, setId, setName, getName } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    // 全局存储token
    token: getToken() || '',
    userId: getId() || null,
    userName: getName() || ''
  },
  mutations: {
    // 定义一个mutations，修改token的数据
    // 存入用户token
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    // 用户ID
    setId(state, userId) {
      state.userId = userId
      setId(userId)
    },
    // 用户名字
    setName(state, userName) {
      state.userName = userName
      setName(userName)
    },
    // 清除token
    removeToken(state) {
      state.token = ''
      state.userInfo = {}
      removeToken()
    }
  },
  actions: {
    // 调用登录接口，获取token数据
    async fetchLogin(store, newloginForm) {
      const { data } = await login(newloginForm)
      store.commit('setToken', data.token)
      store.commit('setId', data.userId)
      store.commit('setName', data.userName)
      console.log(data)
      return data
    },

    // 获取用户信息
    async fetchUserInfo(store) {
      const res = userApi()
      console.log(res)
      store.commit('setUserInfo', res.data)
    }
  }
}
